package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.bean.BuyCarBean;
import com.project.bean.ProductBean;
import com.project.mapper.IBuyCarMapper;
import com.project.mapper.IProductMapper;
import com.project.service.IBuyCarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
@Transactional
public class BuyCarServiceImpl implements IBuyCarService {
    @Autowired
    private IBuyCarMapper buyCarMapper;
    @Autowired
    private IProductMapper productMapper;

    @Override
    public void add(BuyCarBean buyCar) {
        System.out.println(buyCar);
        QueryWrapper<BuyCarBean> qw=new QueryWrapper<>();
        qw.eq("productName",buyCar.getProductName());
        qw.eq("size",buyCar.getSize());
        qw.eq("color",buyCar.getColor());
        qw.eq("userNum",buyCar.getUserNum());
        BuyCarBean buyCarBean=buyCarMapper.selectOne(qw);
        if(buyCarBean!=null){
            buyCarBean.setNum(buyCarBean.getNum()+buyCar.getNum());
            buyCarMapper.updateById(buyCarBean);
        }else {
            buyCarMapper.insert(buyCar);
        }
    }

    @Override
    public void delBuyCar(int buyCarId) {
        buyCarMapper.deleteById(buyCarId);
    }

    @Override
    public String updateNum(int buyCarId, int newNum) {
        BuyCarBean carBean = buyCarMapper.selectById(buyCarId);
        //查看该商品上架量
        QueryWrapper<ProductBean> qw = new QueryWrapper<>();
        qw.eq("productNum", carBean.getProductNum());
        ProductBean product = productMapper.selectOne(qw);
        if (newNum > product.getNum()) {
            return "no";
        } else {
            carBean.setNum(newNum);
            buyCarMapper.updateById(carBean);
            return "ok";
        }
    }

    @Override
    public List<BuyCarBean> findUserBuyCar(Long userNum) {
        QueryWrapper<BuyCarBean> qw = new QueryWrapper<>();
        qw.eq("userNum", userNum);
        return buyCarMapper.selectList(qw);
    }
    
    @Override
    public void del(Long userNum) {
        QueryWrapper<BuyCarBean> qw = new QueryWrapper<>();
        qw.eq("userNum", userNum);
        buyCarMapper.delete(qw);
    }
}
